class ThanNhan < ActiveRecord::Base
  attr_accessible :can_bo_thong_tin_id, :ho_ten, :nam_sinh, :nghe_nghiep, :quan_he_gia_dinh_id, :ghi_chu, :can_bo_thong_tin_name

  attr_accessor :can_bo_thong_tin_name
  #not allow null attributes and custom default message
  validates_presence_of :can_bo_thong_tin_id, :ho_ten, :nam_sinh, :quan_he_gia_dinh_id, :message => "#{Param.get_param_value("is_not_blank")}"


  #relationship
  belongs_to :can_bo_thong_tin
  belongs_to :quan_he_gia_dinh

  def self.is_duplicated(options = {})
     where("can_bo_thong_tin_id = ? AND ho_ten = ?", options[:can_bo_thong_tin_id], options[:ho_ten])
  end

  def self.get_quan_he_id ten_quan_he, allow_add_new = true
    quan_he = QuanHeGiaDinh.find_by_ten_quan_he ten_quan_he
    if quan_he
      return quan_he.id
    end
    if allow_add_new
      #add new QuanHeGiaDinh if not exists
      quan_he = QuanHeGiaDinh.new :ten_quan_he => ten_quan_he, :ghi_chu => 'Generated by controller import from excel'
      quan_he.save
      return quan_he.id
    end
    return 0
  end

  def self.search(search_value)

    if search_value
      where("ho_ten LIKE ? OR can_bo_thong_tin_id in (SELECT id FROM can_bo_thong_tins WHERE ma_cb = ? OR ho_ten LIKE ?)", "%#{search_value}%", search_value, "%#{search_value}%")
    else
      scoped
    end
  end
end